package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.creditx.xbehavior.sdk.ActionName;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.creditx.xbehavior.sdk.PageName;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.entity.UserJob;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.DataVerifyUtils;
import com.zhiqianbao.utils.DialogTypeUtils;
import com.zhiqianbao.utils.DialogWorkIndustryTypeUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.utils.WorkIndustryDataUtils;
import com.zhiqianbao.view.ProcessProgressBarView;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

import static com.zhiqianbao.R.id.put_address;

//import com.lljjcoder.citypickerview.widget.CityPicker;

/**
 * Created by 子龙 on 2017/4/17.
 */

public class FourthActivity extends BaseActivity implements View.OnClickListener {

    private EditText edit_firstId_email;
    private EditText edit_firstId_credit;
    private EditText edit_provice_text;
    private EditText edit_area_text;
    private EditText edit_city_text;
    private Button button_furth_next;
    private EditText edit_firstId_familyChildren;
    private EditText edit_firstId_qq;
    private EditText edit_firstId_job;    private EditText put_address3;
    private EditText edit_second_contactName;
    private EditText editFirstIdFamilyChildrenKey;
    private EditText put_address1;
    private EditText edit_second_contactName2;
    private EditText editFirstIdJobKey;
    private TextView topbar_textview_title;
    private int workMsgIndex = 0;
    private int workMsgSecond = 0;
    private Button button_return;
    SharedPreferanceUtils sharedPreferanceUtils;
    private String nihao;
    private String mput_address;
    private EditText et_my_one;
    private EditText edit_my_key;
    private String[] array_work_msg;
    private DialogTypeUtils typeUtils;
    ProcessProgressBarView processView;
    WorkIndustryDataUtils dataUtils;
    private String startTimes="";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //统计进入工作信息界面开始时间
        startTimes=TimeStatisticsUtil.getTime();

        setContentView(R.layout.activity_fourth);
        dataUtils=new WorkIndustryDataUtils(getResources());
        initView();
        addListner();
        initDate();
        typeUtils=new DialogTypeUtils(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CreditXAgent.onEnteringPage(PageName.PERSONAL_INFO);
    }

    @Override
    public void onPause() {
        super.onPause();
        CreditXAgent.onLeavingPage(PageName.PERSONAL_INFO);
    }

    private void addListner() {
        edit_firstId_credit.setOnClickListener(this);
        button_furth_next.setOnClickListener(this);
        edit_firstId_familyChildren.setOnClickListener(this);
        edit_firstId_job.setOnClickListener(this);
        button_return.setOnClickListener(this);
        et_my_one.setOnClickListener(this);
    }

    private void initView() {
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        edit_firstId_email = (EditText) findViewById(R.id.edit_firstId_email);
        edit_firstId_credit = (EditText) findViewById(R.id.edit_firstId_credit);
        edit_provice_text = (EditText) findViewById(R.id.edit_provice_text);
        edit_area_text = (EditText) findViewById(R.id.edit_area_text);
        edit_city_text = (EditText) findViewById(R.id.edit_city_text);
        button_furth_next = (Button) findViewById(R.id.button_furth_next);
        button_return = (Button) findViewById(R.id.button_return);
        et_my_one = (EditText) findViewById(R.id.et_my_one);
        //标题
        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("工作信息");
        //
        edit_firstId_familyChildren = (EditText) findViewById(R.id.edit_firstId_familyChildren);
        //输入QQ
        edit_firstId_qq = (EditText) findViewById(R.id.edit_firstId_qq);
        //职务
        edit_firstId_job = (EditText) findViewById(R.id.edit_firstId_job);
        //单位名称
        put_address3 = (EditText) findViewById(put_address);
        //单位电话
        edit_second_contactName = (EditText) findViewById(R.id.edit_second_contactName);
        editFirstIdFamilyChildrenKey = (EditText) findViewById(R.id.edit_firstId_familyChildren_key);
        //工作信息
        editFirstIdJobKey = (EditText) findViewById(R.id.edit_firstId_job_key);
        //行业区分
        edit_my_key = (EditText) findViewById(R.id.edit_my_key);
        //单位地址
        put_address1 = (EditText) findViewById(R.id.put_address1);
        mput_address = put_address1.getText().toString().trim();
        //公司电话
        edit_second_contactName2 = (EditText) findViewById(R.id.edit_second_contactName2);

        processView= (ProcessProgressBarView) findViewById(R.id.process_layout);
        //芝麻开启状态,1开启，0未开启
        String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
        if("1".equals(zhimaOpenOrClose)){
            processView.openZhiMaProcess(ProcessProgressBarView.IS_SHOW_ZHIMA,5);
        }
        else{
            processView.openZhiMaProcess(ProcessProgressBarView.NOTIS_SHOW_ZHIMA,4);
        }

    }

    private void initDate() {
        //单位名称
        put_address3.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.PERSONAL_COMPANY_NAME));
        //单位地址
        put_address1.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.PERSONAL_COMPANY_ADDRESS));
        //单位电话
        edit_second_contactName2.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.PERSONAL_COMPANY_PHONE));
        array_work_msg = getResources().getStringArray(R.array.array_work_msg);
    }


    @Override
    public void onClick(View v) {
            if(R.id.edit_firstId_credit==v.getId()) {
//                selectAddress();
                //所属城市
                if (typeUtils != null) {
                    if ((typeUtils.getOptions1Items() != null && (typeUtils.getOptions1Items().size() != 0)) &&
                            (typeUtils.getOptions2Items() != null && (typeUtils.getOptions2Items().size() != 0)) &&
                            (typeUtils.getOptions3Items() != null && (typeUtils.getOptions3Items().size() != 0))) {
                        typeUtils.showPickerView(edit_firstId_credit, edit_provice_text, edit_area_text, edit_city_text);
                    } else {
                        typeUtils.initJsonData(this);
                        typeUtils.showPickerView(edit_firstId_credit, edit_provice_text, edit_area_text, edit_city_text);
                    }
                }
            }
            else if(R.id.edit_firstId_familyChildren==v.getId()) {
                //子女情况
                alertSelectDialog(Constants.CODE_CHILDREN, "请选择子女状况", edit_firstId_familyChildren, editFirstIdFamilyChildrenKey);
            }
            else if(R.id.edit_firstId_job==v.getId()) {
                    //我现在是一名
                    alertSelectDialog(Constants.CODE_WORKJOB, "请选择职位", edit_firstId_job, editFirstIdJobKey);
            }
            else if(R.id.et_my_one==v.getId()) {
                //工作信息
                new DialogWorkIndustryTypeUtils(FourthActivity.this, dataUtils.getOptions1Items(),
                        dataUtils.getOptions2Items(), new DialogWorkIndustryTypeUtils.WorkIndustryCallBack() {
                    @Override
                    public void workInfoCallBack(int firstCode, int secondCode) {
                        workMsgIndex = firstCode;
                        workMsgSecond = secondCode;
                        et_my_one.setText(dataUtils.getFirstWorkMsg(firstCode - 1)
                                + "—" + dataUtils.getSecondtWorkMsg(workMsgSecond));
                    }
                });
            }
            else if(R.id.button_firstIDAuthenActivity_OK_one==v.getId()) {
                    //  startActivity(new Intent(FourthActivity.this,));
            }
            else if(R.id.button_return==v.getId()) {
                finish();
            }
            else if(R.id.button_furth_next==v.getId()) {
                if (!TextUtils.isEmpty(edit_firstId_email.getText().toString().trim())) {
                    if (!DataVerifyUtils.emailValidation(edit_firstId_email.getText().toString().trim())) {
                        showShortToast1("请输入正确格式邮箱");
                        return;
                    }
                }

                //下一步
                if (StringUtils.isBlank(edit_firstId_familyChildren.getText().toString())
                        || StringUtils.isBlank(edit_firstId_qq.getText().toString().trim())
                        || StringUtils.isBlank(edit_firstId_email.getText().toString().trim())
                        || StringUtils.isBlank(edit_firstId_job.getText().toString().trim())
                        || StringUtils.isBlank(edit_firstId_credit.getText().toString().trim())
                        || StringUtils.isBlank(put_address3.getText().toString().trim())
                        || StringUtils.isBlank(edit_second_contactName.getText().toString().trim())
                        || StringUtils.isBlank(et_my_one.getText().toString().trim())
                        ) {
                    showShortToast1("信息要填写完整哦");
                    return;
                }
                //工作
                String job = edit_firstId_job.getText().toString().trim();
                sharedPreferanceUtils.setJob(job);
                String job1 = sharedPreferanceUtils.getJob();
                //所在城市
                String trim_city = edit_firstId_credit.getText().toString().trim();
                sharedPreferanceUtils.setCity(trim_city);
                //单位名称
                String andress_name = put_address3.getText().toString().trim();
                sharedPreferanceUtils.setCompaney(andress_name);
                //单位地址
                String andress1_name = put_address1.getText().toString().trim();
                sharedPreferanceUtils.setAdress(andress1_name);
                String job2 = sharedPreferanceUtils.getJob();
                //区号
                String arenumber = edit_second_contactName.getText().toString().trim();
                sharedPreferanceUtils.setAreaCode(arenumber);
                //电话号码
                String phone_number = edit_second_contactName2.getText().toString().trim();
                sharedPreferanceUtils.setPhoneNuber(phone_number);
                button_furth_next.setEnabled(false);

                //请求第二步信息保存接口，成功后跳转到第三部页面
                Map<String, String> param = new HashMap<>();
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                param.put("qq", edit_firstId_qq.getText().toString().trim());
                param.put("email", edit_firstId_email.getText().toString().trim());
                param.put("children", editFirstIdFamilyChildrenKey.getText().toString().trim());
                param.put("job", editFirstIdJobKey.getText().toString().trim());
                param.put("province", edit_provice_text.getText().toString());
                param.put("city", edit_area_text.getText().toString().trim());
                param.put("area", edit_city_text.getText().toString().toString());
                param.put("companyName", put_address3.getText().toString().trim());
                param.put("companyAddress", put_address1.getText().toString().trim());
                param.put("companyPhone", edit_second_contactName.getText().toString().trim() + edit_second_contactName2.getText().toString().trim());
                param.put("mimidaiVersion", Constants.APP_VERSION);
                param.put("profession",String.valueOf(workMsgIndex));
                param.put("childProfession",String.valueOf(workMsgSecond));
                param.put("mimidaiCode", Constants.APP_CODE + "");

                //添加时间统计
                String endTime= TimeStatisticsUtil.getTime();
                param.put("startTime", startTimes);
                param.put("endTime", endTime);
                new SecondSaveUserInfo().execute(param);

        }
    }

                class SecondSaveUserInfo extends AsyncTask<Map, Void, Result<HashMap>> {
                    @Override
                    protected Result<HashMap> doInBackground(Map... params) {
                        //请求登录接口
                        Message message = new Message();
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/saveJobInfo", params[0], FourthActivity.this);

                        if (StringUtils.isBlank(result)) {
                            return null;
                        }
                        //Result resultObject = gson.fromJson(result, Result.class);
                        Result<HashMap> resultObject = Result.fromJson(result, HashMap.class);
                        return resultObject;
                    }

                    @Override
                    protected void onPreExecute() {
                        showWaitDialog();
                    }

                    @Override
                    protected void onPostExecute(Result<HashMap> result) {
                        if (result == null) {
                            CreditXAgent.onSubmit(ActionName.Submit.PERSONAL_COMPANY_INFO,
                                            CreditXAgent.ActionStatus.FAILED,"提交失败");
                            showShortToast1("连接超时！");
                        } else {
                            //请求成功
                            if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                                CreditXAgent.onSubmit(ActionName.Submit.PERSONAL_COMPANY_INFO,
                                        CreditXAgent.ActionStatus.SUCCESS,"提交成功");
                                button_furth_next.setEnabled(true);
                                User loginUser = gson.fromJson(gson.toJson(result.getData().get("user")), User.class);
                                UserInfo userInfo = gson.fromJson(gson.toJson(result.getData().get("userInfo")), UserInfo.class);
                                UserJob userJob = gson.fromJson(gson.toJson(result.getData().get("userJob")), UserJob.class);

                                Constants.LOGIN_USER = loginUser;
                                User.deleteAll(User.class);
                                loginUser.save();
                                UserInfo.deleteAll(UserInfo.class);
                                userInfo.save();
                                UserJob.deleteAll(UserJob.class);
                                userJob.save();
                                String profession=userJob.getProfession();
                                String childProfession=userJob.getChildProfession();
                                if((!TextUtils.isEmpty(profession))&&(!TextUtils.isEmpty(childProfession))){
                                    sharedPreferanceUtils.setUserJobProfession(profession+"-"+childProfession);
                                }
                                else{
                                    sharedPreferanceUtils.setUserJobProfession("");
                                }
                                SharedPreferanceUtils.setJob(edit_firstId_job.getText().toString().trim());
                                //认证成功
                                startActivity(new Intent(FourthActivity.this, CertificationSdActivity.class));
                                FourthActivity.this.finish();
                            } else {
                                CreditXAgent.onSubmit(ActionName.Submit.PERSONAL_COMPANY_INFO,
                                        CreditXAgent.ActionStatus.FAILED,"提交失败");
                                showShortToast1(result.getMsg());
                            }
                        }
                        closeWaitDialog();
                    }
                }

//    private void selectAddress() {
//
//        CityPicker cityPicker = new CityPicker.Builder(FourthActivity.this)
//                .textSize(14)
//                .title("地址选择")
//                .titleBackgroundColor("#FFFFFF")
//                .confirTextColor("#696969")
//                .cancelTextColor("#696969")
//                .province("江苏省")
//                .city("常州市")
//                .district("天宁区")
//                .textColor(Color.parseColor("#000000"))
//                .provinceCyclic(true)
//                .cityCyclic(false)
//                .districtCyclic(false)
//                .visibleItemsCount(7)
//                .itemPadding(10)
//                .onlyShowProvinceAndCity(false)
//                .build();
//        cityPicker.show();
//        //监听方法，获取选择结果
//        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
//            @Override
//            public void onSelected(String... citySelected) {
//                //省份
//                String province = citySelected[0];
//                //城市
//                String city = citySelected[1];
//                //区县（如果设定了两级联动，那么该项返回空）
//                String district = citySelected[2];
//                //邮编
//                String code = citySelected[3];
//                Log.i("FourthActivityAdress",province.trim() + "-" + city.trim() + "-" + district.trim());
//            }
//        });
//    }
}


